package jmine.tec.persist.schema.impl.parsers;

import java.util.regex.Matcher;

import jmine.tec.persist.schema.impl.elements.CommentElement;
import jmine.tec.persist.schema.impl.elements.Schema;

/**
 * Parser de comments
 * 
 * @author lundberg
 */
public class CommentParser extends AbstractSchemaElementParser<CommentElement> {

    private static final int TABLE_NAME_GROUP_INDEX = 1;

    private static final int COLUMN_NAME_GROUP_INDEX = 2;

    private static final int COMMENT_GROUP_INDEX = 3;

    /**
     * Construtor
     * @param schema schema
     */
    public CommentParser(Schema schema) {
        super("comment\\s+on\\s+(?:table|column)\\s+(\\w+)(?:\\.(\\w+))?\\s+is\\s+'(.+)'", schema);
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CommentElement doParse(Matcher matcher) {
        String table = matcher.group(TABLE_NAME_GROUP_INDEX);
        String comment = matcher.group(COMMENT_GROUP_INDEX).replaceAll("''", "'");
        if (matcher.group(COLUMN_NAME_GROUP_INDEX) != null) {
            return new CommentElement(table, matcher.group(COLUMN_NAME_GROUP_INDEX), comment);
        } else {
            return new CommentElement(table, comment);
        }
    }
}
